#!/bin/bash
# ONVIF摄像头管理系统 - 统一启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

VENV_DIR="venv"
PROJECT_NAME="ONVIF Camera Manager"

# 显示帮助信息
show_help() {
    echo -e "${BLUE}$PROJECT_NAME - 统一启动脚本${NC}"
    echo
    echo "用法: $0 [命令]"
    echo
    echo "命令:"
    echo "  setup     - 安装环境和依赖"
    echo "  start     - 启动程序 (默认)"
    echo "  clean     - 清理环境"
    echo "  help      - 显示此帮助信息"
    echo
}

# 检查Python版本
check_python() {
    if ! command -v python3 &> /dev/null; then
        echo -e "${RED}错误: 未找到python3命令${NC}"
        echo "请安装Python 3.8或更高版本"
        exit 1
    fi
    
    if ! python3 -c "import sys; exit(0 if sys.version_info >= (3, 8) else 1)" 2>/dev/null; then
        echo -e "${RED}错误: Python版本过低，需要3.8或更高版本${NC}"
        exit 1
    fi
}

# 设置环境
setup_env() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  $PROJECT_NAME 环境安装${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo
    
    # 检查是否在项目根目录
    if [ ! -f "main.py" ]; then
        echo -e "${RED}错误: 请在项目根目录运行此脚本${NC}"
        exit 1
    fi
    
    # 检查Python
    echo -e "${YELLOW}检查Python环境...${NC}"
    check_python
    PYTHON_VERSION=$(python3 -c "import sys; print('.'.join(map(str, sys.version_info[:2])))")
    echo -e "${GREEN}✓ Python版本: $PYTHON_VERSION${NC}"
    echo
    
    # 创建虚拟环境
    echo -e "${YELLOW}设置虚拟环境...${NC}"
    if [ -d "$VENV_DIR" ]; then
        echo "虚拟环境已存在，跳过创建"
    else
        echo "创建虚拟环境: $VENV_DIR"
        python3 -m venv "$VENV_DIR"
        echo -e "${GREEN}✓ 虚拟环境创建成功${NC}"
    fi
    echo
    
    # 激活虚拟环境并安装依赖
    echo -e "${YELLOW}安装依赖包...${NC}"
    source "$VENV_DIR/bin/activate"
    
    # 升级pip
    python -m pip install --upgrade pip --quiet
    
    # 安装依赖
    if [ ! -f "requirements.txt" ]; then
        echo -e "${RED}错误: 未找到requirements.txt文件${NC}"
        exit 1
    fi
    
    pip install -r requirements.txt --quiet
    echo -e "${GREEN}✓ 依赖安装完成${NC}"
    echo
    
    # 验证关键模块
    echo -e "${YELLOW}验证安装...${NC}"
    python -c "import ping3, yaml, loguru, prometheus_client" 2>/dev/null
    echo -e "${GREEN}✓ 所有依赖验证通过${NC}"
    echo
    
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  环境安装完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo
    echo -e "${BLUE}使用方法:${NC}"
    echo "  ./run.sh start          # 启动程序"
    echo "  ./run.sh clean          # 清理环境"
    echo
    echo -e "${BLUE}配置文件:${NC}"
    echo "  config/config.yaml      # 主配置文件"
    echo
    echo -e "${BLUE}Prometheus监控:${NC}"
    echo "  http://localhost:9098/metrics  # 指标端点"
    echo
}

# 启动程序
start_program() {
    # 检查虚拟环境
    if [ ! -d "$VENV_DIR" ]; then
        echo -e "${YELLOW}虚拟环境不存在，正在自动安装...${NC}"
        setup_env
        echo
    fi
    
    # 检查是否在项目根目录
    if [ ! -f "main.py" ]; then
        echo -e "${RED}错误: 请在项目根目录运行此脚本${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}启动 $PROJECT_NAME...${NC}"
    echo
    
    # 激活虚拟环境并启动程序
    source "$VENV_DIR/bin/activate"
    python main.py
}

# 清理环境
clean_env() {
    echo -e "${YELLOW}清理环境...${NC}"
    
    # 删除虚拟环境
    if [ -d "$VENV_DIR" ]; then
        echo "删除虚拟环境..."
        rm -rf "$VENV_DIR"
        echo -e "${GREEN}✓ 虚拟环境已删除${NC}"
    fi
    
    # 删除Python缓存
    echo "清理Python缓存..."
    find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
    find . -name "*.pyc" -delete 2>/dev/null || true
    find . -name "*.pyo" -delete 2>/dev/null || true
    
    # 询问是否删除数据文件
    echo
    echo "是否删除设备数据文件 devices.json? (y/N)"
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        rm -f devices.json
        echo -e "${GREEN}✓ 数据文件已删除${NC}"
    fi
    
    echo -e "${GREEN}✓ 环境清理完成${NC}"
}

# 主函数
main() {
    case "${1:-start}" in
        setup)
            setup_env
            ;;
        start)
            start_program
            ;;
        clean)
            clean_env
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            echo -e "${RED}未知命令: $1${NC}"
            echo
            show_help
            exit 1
            ;;
    esac
}

main "$@"
